package com.edu.admin.common;

import java.util.HashMap;
import java.util.Map;

import com.edu.admin.entity.SysAdmin;

/**
 * 线程变量
 * 
 * @author Wangjiong
 */
public class BaseContextHandler {
	
	public static final String CONTEXT_KEY_ADMIN_ID = "currentAdminId";
	public static final String CONTEXT_KEY_ADMIN_TOKEN = "currentAdminToken";
	public static final String CONTEXT_KEY_ADMIN = "currentAdmin";
	public static final String CONTEXT_KEY_ADMIN_ROLE_URLS = "currentAdminRoleUrls";
	
	public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

	public static void set(String key, Object value) {
		Map<String, Object> map = threadLocal.get();
		if (map == null) {
			map = new HashMap<String, Object>();
			threadLocal.set(map);
		}
		map.put(key, value);
	}

	public static Object get(String key) {
		Map<String, Object> map = threadLocal.get();
		if (map == null) {
			map = new HashMap<String, Object>();
			threadLocal.set(map);
		}
		return map.get(key);
	}

	public static Long getAdminId() {
		Object value = get(CONTEXT_KEY_ADMIN_ID);
		return value == null ? null : Long.valueOf(value.toString());
	}

	public static String getToken() {
		Object value = get(CONTEXT_KEY_ADMIN_TOKEN);
		return getObjectValue(value);
	}
	
	public static SysAdmin getAdmin() {
		Object admin = get(CONTEXT_KEY_ADMIN);
		return admin == null ? null : (SysAdmin) admin;
	}
	
	public static String getRoleUrls() {
		Object roleUrls = get(CONTEXT_KEY_ADMIN_ROLE_URLS);
		return getObjectValue(roleUrls);
	}

	public static void setToken(String token) {
		set(CONTEXT_KEY_ADMIN_TOKEN, token);
	}

	public static void setAdminId(Long adminId) {
		set(CONTEXT_KEY_ADMIN_ID, adminId);
	}

	public static void setAdmin(SysAdmin admin) {
		set(CONTEXT_KEY_ADMIN, admin);
	}
	
	public static void setRoleUrls(String roleUrls) {
		set(CONTEXT_KEY_ADMIN_ROLE_URLS, roleUrls);
	}

	public static void remove() {
		threadLocal.remove();
	}

	public static String getObjectValue(Object obj) {
		return obj == null ? "" : obj.toString();
	}
}
